package chances.epg.session;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import chances.epg.commons.utils.SpringWebUtils;
import chances.epg.commons.utils.URLUtils;
import chances.epg.config.EpgSiteContext;
import chances.epg.navigator.service.NavigateUrlFactory;
import chances.epg.play.ctrl.PlayController;
import chances.epg.session.ctrl.LogonController;

public class UserSessionInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (HandlerMethod.class.isInstance(handler)) {
			HandlerMethod aHanlderMeethod = (HandlerMethod) handler;
			if(isNotHandler(aHanlderMeethod)){
				return true;
			}
		}

		UserSession userSession = UserSessionHelper.getUserSession(request);
		if(userSession==null){
			userSession = UserSessionHelper.getUserSessionFromCookie(request);
			
		}
		if (userSession != null) {
			userSession.setCurrentUrl(request.getServletPath());
			userSession.setLastActiveTime(System.currentTimeMillis());
			request.setAttribute("userSession", userSession);
			return true;
		} else {
			@SuppressWarnings("unchecked")
			Map<String, String> uriTemplateVariables = (Map<String, String>) request
					.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
			String siteCode = uriTemplateVariables.get("siteCode");
			
			NavigateUrlFactory navigateUrlFactory = SpringWebUtils.findBean(request, NavigateUrlFactory.class);
			if(siteCode == null || siteCode.equals(navigateUrlFactory.getMprogram())){
				return true;
			}
			String loginPath = request.getContextPath() + request.getServletPath();
			EpgSiteContext epgSiteContext = EpgSiteContext.get(request.getServletContext(), siteCode);
			String path = navigateUrlFactory.generateLoginUrl(epgSiteContext);
		    String queryString = request.getQueryString();
		    if(StringUtils.isNotEmpty(queryString)){
		    	 path = path+"?"+queryString;
				 path = URLUtils.appendParam(path, "loginUrl", loginPath);
		    }else{
		    	 path = URLUtils.appendParam(path, "loginUrl", loginPath);
		    }
		    response.sendRedirect(path);
			return false;
		}
	}

	private boolean isNotHandler(HandlerMethod aHanlderMeethod) {
		if (LogonController.class.isInstance(aHanlderMeethod.getBean()) || PlayController.class.isInstance(aHanlderMeethod.getBean())) {
			return true;
		}else{
			return false;
		}
	}

}
